package com.xtaller.sdboot.controller;

import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
import com.xtaller.sdboot.core.R;
import com.xtaller.sdboot.core.Status;
import com.xtaller.sdboot.core.base.OriginalController;
import com.xtaller.sdboot.util.OssUtil;
import com.xtaller.sdboot.utils.annotation.Token;
import com.xtaller.sdboot.utils.bean.STS;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author : Taller
 * @date : 2020/3/18 14:50
 * @Description : 第三方控制器
 */
@RestController
@RequestMapping("/v1/tps")
public class TpsController extends OriginalController {
    @Autowired private STS sts;

    @ApiOperation("获取阿里OSS授权")
    @Token
    @GetMapping("/sts")
    public Object getSTS(){
        String accessKeyId = sts.getAccessKeyID();
        String accessKeySecret = sts.getAccessKeySecret();
        String roleArn = sts.getRoleArn();
        long durationSeconds = sts.getTokenExpireTime();
        String policy = sts.getPolicy();
        String bucket = sts.getBucket();
        String region = sts.getRegion();

        ProtocolType protocolType = ProtocolType.HTTPS;
        Map<String, String> respMap = new LinkedHashMap<String, String>();

        try {
            final AssumeRoleResponse stsResponse =
                    OssUtil.assumeRole(region,accessKeyId,accessKeySecret, roleArn,
                            bucket,policy, protocolType, durationSeconds);

            respMap.put("AccessKeyID", stsResponse.getCredentials().getAccessKeyId());
            respMap.put("AccessKeySecret", stsResponse.getCredentials().getAccessKeySecret());
            respMap.put("SecurityToken", stsResponse.getCredentials().getSecurityToken());


            respMap.put("Bucket", bucket);
            respMap.put("Region", "oss-" + sts.getRegion());
            respMap.put("Endpoint",sts.getEndpoint());
            return R.ok(respMap);
        } catch (com.aliyuncs.exceptions.ClientException e) {
            return R.error(Status.BAD_REQUEST, "授权失败");
        }
    }
}
